package battleship;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Editprofile extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException
	{
		try {
			aditAvatar(req, res);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		res.sendRedirect("index.jsp");
		
	}
	private static void aditAvatar(HttpServletRequest req, HttpServletResponse res) throws IOException, SQLException {
		
		PrintWriter out = res.getWriter();
		final HttpSession session = req.getSession(true);
		final Connection con =  Database.open();
		String avatarId = req.getParameter("avatar");
	
		PreparedStatement updateAvatar = con.prepareStatement("update user set avatar= ? where uid= ?");
		updateAvatar.setString(1, avatarId);
		updateAvatar.setString(2, (String) session.getAttribute(Constants.ATTR_UID));
		updateAvatar.executeUpdate();
		
	}
	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException
	{
		
		try {	
				editNickname(req,res);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}

	public static void editNickname(HttpServletRequest req, HttpServletResponse res) 
		throws SQLException, IOException{
		PrintWriter out = res.getWriter();
		final HttpSession session = req.getSession(true);
		final Connection con =  Database.open();
		String nickname = req.getParameter("newNickname");
		PreparedStatement ps = con
		.prepareStatement("select * from User where nickname=?");
		ps.setString(1, nickname);
		final ResultSet rs = ps.executeQuery();
		if (rs.next()) 
		{
			System.out.println("Nickname already in use!");
		}
		else
		{
		PreparedStatement updateNickname = con.prepareStatement("update user set nickname= ? where uid= ?");
		updateNickname.setString(1, nickname);
		updateNickname.setString(2, ""+session.getAttribute(Constants.ATTR_UID));
		out.println(nickname);
		out.println(session.getAttribute(Constants.ATTR_UID));
		updateNickname.executeUpdate();
		session.setAttribute(Constants.ATTR_NICKNAME,nickname);
		}
		res.sendRedirect("editprofile.jsp?message=Nickname%20successfully%20changed to: "+nickname);
		
	}
	
}
